<?php
/**
 * 老请假记录数据转换到审批列表
 * 1.已撤销的数据不做转换
 * 2.已批准假期 都显示在一级领导那边（二级领导不做处理）
 * 3.未审批的直接写入一级领导记录
 * 4.二级领导是bos的不导入
 * 5.已审核的大于3天的导入二级领导
 * 6.出差的特殊处理
 */
error_reporting(E_ALL);
apf_require_class('Oa_Job_Attendance_Abstract');
class Oa_Job_Attendance_ConvertAuditList extends Oa_Job_Attendance_Abstract {
    /** 考勤系统读 **/
    private $readdb = "attendance_slave";
    /** 考勤系统写 **/
    private $writedb = "attendance_master";

    private $trip_manager;

    public function run(){
        $this->log("开始查询...");
        $this->trip_manager = $this->get_trip_manager_info();
        $this->init_data();
        $this->log("更新完毕");
    }


    /**
     * 写入记录
     */
    private function init_data(){
        $sql = "REPLACE INTO audit_list(uid,leave_id,status) VALUES(?,?,?)";
        $all_record = $this->get_all_record_list();

        $email_list = array(
                'michaellv@anjukeinc.com',
                'garyhu@anjukeinc.com',
                'julianwang@anjukeinc.com',
                'justin@anjukeinc.com',
                'joychen@anjukeinc.com',
                'echoyang@anjukeinc.com',
                'vincentchang@anjukeinc.com',
                'henrytang@anjukeinc.com'
        );

        //导入未审批数据
        foreach ($all_record['notyet'] as $record){
            if($record['type'] == "出差"){
                //特殊处理下uid
                $trip = $this->trip_manager;
                $record['r_user_id'] = $trip[$record['department_id']]['user_id'];
                //特殊处理-------------------------
                if(in_array($record['email'],$email_list)){
                     $record['r_user_id'] = $this->get_boss_id();//审批者为mike
                }
            }

            if($record['r_user_id']<1){
                $this->log("请假记录错误，没有上级批准");
                continue;
            }
            $this->execute($sql,array($record['r_user_id'],$record['id'],1),$this->writedb);
        }
        //导入已审批的数据,只显示一级领导的
        foreach($all_record['ok'] as $record){
            if($record['type'] == "出差"){
                //特殊处理下uid
                $trip = $this->trip_manager;
                $record['r_user_id'] = $trip[$record['department_id']]['user_id'];
                //特殊处理-------------------------
                if(in_array($record['email'],$email_list)){
                    $record['r_user_id'] = $this->get_boss_id();//审批者为mike
                }
            }


            if($record['r_user_id']<1){
                $this->log("请假记录错误，没有上级批准");
                continue;
            }
            $this->execute($sql,array($record['r_user_id'],$record['id'],2),$this->writedb);

            $bos_id = $this->get_boss_id();
            //大于三天的假 ,如果二级领导是bos，也不写入
            if($record['b_user_id']>0 and $record['type'] !='出差' and $record['leave_time'] >3 and $record['b_user_id'] != $bos_id){
                $this->execute($sql,array($record['b_user_id'],$record['id'],2),$this->writedb);
            }
        }
        //导入已驳回的记录
        foreach ($all_record['no'] as $record){
            if($record['type'] == "出差"){
                //特殊处理下uid
                $trip = $this->trip_manager;
                $record['r_user_id'] = $trip[$record['department_id']]['user_id'];
                //特殊处理-------------------------
                if(in_array($record['email'],$email_list)){
                    $record['r_user_id'] = $this->get_boss_id();//审批者为mike
                }
            }


            if($record['r_user_id']<1){
                $this->log("请假记录错误，没有上级批准");
                continue;
            }
            $this->execute($sql,array($record['r_user_id'],$record['id'],2),$this->writedb);
        }

        //处理已撤销数据
        $this->change_status($all_record);
    }

    /**
     * 对已撤销但是在audit_list 表中状态还存在的数据进行更新操作，状态改为3
     */
    public function change_status($all_record) {
        // 过滤出所有已撤销记录
        foreach ( $all_record['cancel'] as $record ) {
            if ($record['status'] == '已撤销') {
                // 小于等于三天和出差，由一个人审批的
                apf_require_class ( 'Bll_Attendance_LeaveRecordLog' );
                $record_log_bll = new Bll_Attendance_LeaveRecordLog ();
                $record_logs = $record_log_bll->get_log_by_ids ( $record ['id'] );
                $count_record_logs = count ( $record_logs );

                // 取audit_list 记录
                apf_require_class ( 'Bll_Attendance_Audit' );
                $audit_bll = new Bll_Attendance_Audit ();
                $audit_lists = $audit_bll->get_audit_by_leave_id ( $record ['id'] );
                $count_audit = count ( $audit_lists );

                if ($record ['type'] == '出差' or $record ['leave_time'] <= 3) {
                    if ($count_audit and $audit_lists[0]['status'] ==1) { // 已经在未审批里面了,已审批就不管
                        $this->log ( '更新数据 类型1...' );
                        $audit_bll->update_audit_list ( array (
                                'status' => 3
                        ), array (
                                'leave_id' => $record ['id']
                        ) );
                    }
                } 				// 2. 大于三天的假期
                else {
                    if ($count_audit == 1) {
                        // 判断一级领导是否有批准，未批准做更新操作，已批不做操作
                        if ($audit_lists [0] ['status'] == 1) {
                            $this->log ( '更新数据 类型2...' );
                            $audit_bll->update_audit_list ( array (
                                    'status' => 3
                            ), array (
                                    'leave_id' => $record ['id'],
                                    'uid' => $record ['r_user_id']
                            ) );
                        }
                    } elseif ($count_audit == 2 and $audit_lists [1] ['status'] == 1) { // 只有二级领导没有审批，更新其状态
                        $this->log ( '更新数据 类型3...' );
                        $audit_bll->update_audit_list ( array (
                                'status' => 3
                        ), array (
                                'leave_id' => $record ['id'],
                                'uid' => $record ['b_user_id']
                        ) );
                    }
                }
            }
        }
    }


    /**
     * 所有请假记录
     */
    public function get_all_record_list(){
        $offset = 0;
        $limit = 100;
        $data = array();
        do{
            $rows = $this->get_record_list($offset,$limit);
            foreach ($rows as $row){
                if($row['status'] !='已撤销'){//过滤掉已撤销
                    if($row['status'] == '已批准'){
                        $data['ok'][] = $row;
                    }
                    elseif ($row['status'] == '已驳回'){
                        $data['no'][] = $row;
                    }
                    else{
                        //未审核的，貌似有的还有个二级
                        $data['notyet'][] = $row;
                    }
                }
                else{//已撤销的
                    $data['cancel'][] = $row;
                }
            }
            $offset += $limit;
        }while(!empty($rows));
        return $data;
    }

    /**
     * 分批取请假记录
     * @param int $offset
     * @param int $limit
     */
    public function get_record_list($offset,$limit = 100){
        $data = array();
        $sql = "set names utf8";
        $this->execute($sql,array(),$this->readdb);
        $sql = "select r.*,u.name,u.department_id,u.email from leave_record r,user_info u where r.user_id = u.user_id limit {$offset},{$limit}";
        $rows = $this->get_db_rows($sql, $this->readdb);
        return $rows;
    }

    /**
     * 获取所有出差管理信息
     */
    public function get_trip_manager_info(){
        $sql = "select * from trip_manager";
        $result = $this->get_db_rows($sql, $this->readdb);
        $date = array();
        foreach($result as $r){
            $date[$r['department_id']] = $r;
        }
        return $date;
    }

    private function get_boss_id(){
        //TODO 可配置code
        $code = "SHA001";
        $sql = "select * from user_info where code = '$code' ";
        $row = $this->get_db_row($sql, $this->readdb);
        $this->boss_id = $row['user_id'];
        return $row['user_id'];
    }
}